package com.example.cinemasystemv2.repository;

import com.example.cinemasystemv2.entity.Order;
import com.example.cinemasystemv2.entity.Screening;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface OrderRepository extends JpaRepository<Order, String> {
    
    List<Order> findByUsername(String username);
    
    List<Order> findByScreening(Screening screening);
    
    @Query("SELECT o FROM Order o WHERE o.screening = :screening AND o.row = :row AND o.seat = :seat AND o.isRefunded = false")
    List<Order> findBySeat(@Param("screening") Screening screening, @Param("row") int row, @Param("seat") int seat);
    
    @Query("SELECT o FROM Order o WHERE DATE(o.orderTime) = DATE(:date)")
    List<Order> findByOrderDate(@Param("date") LocalDateTime date);
    
    @Query("SELECT o FROM Order o WHERE o.orderTime >= :startTime AND o.orderTime < :endTime")
    List<Order> findByDateRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
    
    @Query("SELECT SUM(o.amount) FROM Order o WHERE DATE(o.orderTime) = DATE(:date) AND o.isRefunded = false")
    Double getTotalSalesByDate(@Param("date") LocalDateTime date);
    
    @Query("SELECT SUM(o.amount) FROM Order o WHERE o.orderTime >= :startTime AND o.orderTime < :endTime AND o.isRefunded = false")
    Double getTotalSalesByDateRange(@Param("startTime") LocalDateTime startTime, @Param("endTime") LocalDateTime endTime);
    
    @Query("SELECT COUNT(o) FROM Order o WHERE o.screening = :screening AND o.isRefunded = false")
    long countSoldTickets(@Param("screening") Screening screening);
    
    List<Order> findByIsRefunded(boolean isRefunded);
}